package com.lhkj.ct.meta.modules.scheduling.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.base.mybatis.core.metadata.SqlOrder;
import com.lhkj.ct.base.mybatis.extension.service.impl.IServiceImpl;
import com.lhkj.ct.base.utils.Validate;
import com.lhkj.ct.meta.modules.scheduling.mapper.ScheMouldMapper;
import com.lhkj.ct.meta.modules.scheduling.model.entity.TblScheMould;
import com.lhkj.ct.meta.modules.scheduling.service.ScheMouldService;
import com.lhkj.ct.meta.modules.scheduling.service.ScheMouldTimeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * <p>
 * 排班模板 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-10-29
 */
@Service
public class ScheMouldServiceImpl extends IServiceImpl<ScheMouldMapper, TblScheMould> implements ScheMouldService {

    @Resource
    private ScheMouldTimeService scheMouldTimeService;

    @Override
    public IPage<TblScheMould> selectMouldPage(TblScheMould mould, PageQuery pageQuery) {
        return getBaseMapper().selectMouldPage(
                generatePage(pageQuery, SqlOrder.desc(TblScheMould::getCreateTime)),
                mould
        );
    }

    @Override
    public TblScheMould getById(Serializable id) {
        TblScheMould mould = getBaseMapper().selectById(id);
        Validate.notNull(mould, "排班模板不存在或已删除！");
        mould.setTimes(scheMouldTimeService.selectAllByMouldId(mould.getId()));
        return mould;
    }

    @Override
    public int insert(TblScheMould entity) {
        int res = getBaseMapper().insert(entity);
        entity.getTimes().forEach(p -> p.setMouldId(entity.getId()));
        scheMouldTimeService.saveBatch(entity.getTimes());
        return res;
    }

    @Override
    public int updateById(TblScheMould entity) {
        int res = getBaseMapper().updateById(entity);
        scheMouldTimeService.deleteByMouldId(entity.getId());
        entity.getTimes().forEach(p -> p.setMouldId(entity.getId()));
        scheMouldTimeService.saveBatch(entity.getTimes());
        return res;
    }
}
